package com.app.studyroom.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.app.studyroom.R;

import java.util.ArrayList;
import java.util.List;

public class PinCodeView extends LinearLayout {
    private int length = 6;
    private List<ImageView> dots = new ArrayList<>();
    private StringBuilder input = new StringBuilder();

    public interface OnInputCompleteListener {
        void onComplete(String code);
    }

    private OnInputCompleteListener listener;

    public void setOnInputCompleteListener(OnInputCompleteListener l) {
        this.listener = l;
    }

    public PinCodeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        setOrientation(HORIZONTAL);
        setGravity(Gravity.CENTER);
        for (int i = 0; i < length; i++) {
            ImageView dot = new ImageView(getContext());
            LayoutParams lp = new LayoutParams(30, 30);
            lp.setMargins(20, 20, 20, 20);
            dot.setLayoutParams(lp);
            dot.setImageResource(R.drawable.dot_empty); // 圆圈未填充
            dots.add(dot);
            addView(dot);
        }
    }

    public void inputDigit(String digit) {
        if (input.length() < length) {
            input.append(digit);
            updateDots();
            if (input.length() == length && listener != null) {
                listener.onComplete(input.toString());
            }
        }
    }

    public void deleteLast() {
        if (input.length() > 0) {
            input.deleteCharAt(input.length() - 1);
            updateDots();
        }
    }

    public void clear() {
        input.setLength(0);
        updateDots();
    }

    private void updateDots() {
        for (int i = 0; i < dots.size(); i++) {
            dots.get(i).setImageResource(i < input.length() ? R.drawable.dot_filled : R.drawable.dot_empty);
        }
    }
}